//
//  BuildingViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/9/13.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "BuildingViewController.h"
#import "RentVieitor.h"
#import "RentFindParkView.h"
#import "FangModel.h"
#import "BuildingModel.h"
#import "MJRefresh.h"
#import "AllHouseCell.h"
#import "ParkCell.h"
#import "ParkDetailVC.h"
@interface BuildingViewController ()<RentFindParkViewDeleget,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@end

@implementation BuildingViewController{
    
    UITableView *_tableview;
    NSString *_identify;
    RentFindParkView *optinView;
    NSString *rent_start;//最小租金
    NSString *rent_end;//最大租金'
    NSString *bedroom;//卧室数量
    NSString *characteristic;//特色
    NSString *district;//区域
    NSInteger page;//页码
    NSString *title;//搜索关键字
    UITextField *field;
    NSArray *moneyStart;
    NSArray *moneyEnd;
    
}



- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatLeftView];
//    self.title = @"功能完善中";
    self.view.backgroundColor = BackgroundColor;
//    [self creatview];
    self.data = [NSMutableArray array];
    self.view.backgroundColor = BackgroundColor;
    self.title = @"在租房源";
    page = 1;
    if (self.agent == nil) {
        self.agent = @"";
    }
    moneyStart = @[@"",@"1",@"3000",@"4000",@"5000",@"6000",@"7000",@""];
    moneyEnd = @[@"",@"3000",@"4000",@"5000",@"6000",@"7000",@"10000",@""];
    [self creatLeftView];
    [self creatView];
    [self reloadData];
    [self creatNavigationView];

}

- (void)creatLeftView {
    
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 10,20 );
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backActions) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏右侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 20, 20);
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"搜索icon"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
}

- (void)creatView{
    _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, KWidth, KHeight-40) style:UITableViewStylePlain];
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview .showsHorizontalScrollIndicator = NO;
    _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _identify = @"_Cell";
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KWidth*200/750)];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KWidth*200/750)];
    [view addSubview:imgView];
    imgView.image = [UIImage imageNamed:@"rent_heard"];
    _tableview.tableHeaderView = view;
    
    
    [self.view addSubview:_tableview];
    
    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh)];
    [_tableview registerClass:[ParkCell class] forCellReuseIdentifier:_identify];
    
    optinView = [[RentFindParkView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 40) deleget:self];
    [optinView becomeFirstResponder];
    [self.view addSubview:optinView];

    
}

- (void)reloadData{
    
    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    page = 1;
    if (bedroom == nil) {
        bedroom = @"";
    }
    if (district == nil) {
        district = @"";
    }
    if (characteristic == nil) {
        characteristic = @"";
    }
    if (rent_start == nil) {
        rent_start = @"";
    }
    if (rent_end == nil) {
        rent_end = @"";
    }
    if (title == nil) {
        title = @"";
    }
    NSString *url = [NSString stringWithFormat:@"%@xq/list",Main_Url];
    NSDictionary *dic = @{
                          @"district":@"",
                          @"city":@"103",
                          @"region":@"",
                          @"name":@"",
                          @"row":@"10",
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        if ([response[@"code"] isEqualToString:@"10000"]) {
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                BuildingModel *model = [[BuildingModel alloc]initWithDictionary:dic error:nil];
                [WeakSelf.data addObject:model];
            }
            NSLog(@"data.count=%ld",WeakSelf.data.count);
            [_tableview   reloadData];
//            [_tableview.mj_header endRefreshing];
            if (WeakSelf.data.count == 5) {
                page ++;
            }
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
//        [_tableview.mj_header endRefreshing];
    }];
    
}

//下拉刷新
- (void)headerRefresh {
    
    
    bedroom = @"";
    district = @"";
    characteristic = @"";
    rent_start = @"";
    rent_end = @"";
    title = @"";
    
    [self.data removeAllObjects];
    if (self.data == nil) {
        self.data = [NSMutableArray array];
    }
    [self reloadData];

    
}

- (void)footRefresh {
    page ++;
    __weak typeof(self)WeakSelf = self;
    /*
    NSString *url = [NSString stringWithFormat:@"%@fang/list",Main_Url];
    NSDictionary *dic = @{
                          @"category":@"1001",
                          @"city":@"103",
                          @"bedroom":bedroom,
                          @"district":district,
                          @"characteristic":characteristic,
                          @"rent_start":rent_start,
                          @"rent_end":rent_end,
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          @"title":title
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSArray *dataArray = response[@"data"];
            if (dataArray.count <10) {
                page --;
            }
            for (NSDictionary *dic in dataArray) {
                
                FangModel *model = [[FangModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [WeakSelf.data addObject:model];
            }
            
            [_tableview   reloadData];
            [_tableview.mj_footer endRefreshing];
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        page --;
        
    }];
     */
    NSString *url = [NSString stringWithFormat:@"%@xq/list",Main_Url];
    NSDictionary *dic = @{
                          @"district":@"",
                          @"city":@"103",
                          @"region":@"",
                          @"name":@"",
                          @"row":@"10",
                          @"page":[NSString stringWithFormat:@"%ld",page],
                          };
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        if ([response[@"code"] isEqualToString:@"10000"]) {
            NSArray *dataArray = response[@"data"];
            for (NSDictionary *dic in dataArray) {
                BuildingModel *model = [[BuildingModel alloc]initWithDictionary:dic error:nil];
                [WeakSelf.data addObject:model];
            }
            [_tableview   reloadData];
            [_tableview.mj_footer endRefreshing];
            if (WeakSelf.data.count == 5) {
                page ++;
            }
        }else {
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
                [_tableview.mj_header endRefreshing];
    }];
    [_tableview.mj_footer endRefreshing];
}

- (void)creatNavigationView{
    //搜索视图
    UIView *naView = [[UIView alloc] init];
    naView.layer.masksToBounds = YES;
    naView.layer.cornerRadius = 5;
    naView.backgroundColor = [UIColor whiteColor];
    naView.layer.borderWidth = 1;
    naView.layer.borderColor = [Utils colorConvertFromString:@"#999999"].CGColor;
    naView.frame = CGRectMake(30, 60, KWidth-110, 30);
    field = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, naView.frame.size.width-60, 30)];
    field.delegate = self;
    field.font = [UIFont systemFontOfSize:14];
    field.leftViewMode = UITextFieldViewModeAlways;
    [naView  addSubview:field];
    field.placeholder = @"请输入小区名称进行搜索";
    self.navigationItem.titleView = naView;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 15)];
    UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    [leftView addSubview:imgview];
    imgview.image = [UIImage imageNamed:@"搜索icon"];
    field.leftView = leftView;

}
- (void)creatview {
    
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 250/2, KWidth-200, (KWidth-160)*257/592)];
    imgView.image = [UIImage imageNamed:@"lackimg"];
    [self.view addSubview:imgView];
    
    UILabel *proLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,250/2+(KWidth-200)*257/592+30,  KWidth, 20)];
    proLabel.text = @"该功能正在完善中";
    proLabel.textColor = [Utils colorConvertFromString:@"#101010"];
    proLabel.font = [UIFont systemFontOfSize:15];
    proLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proLabel];
    
    UILabel *proLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0,250/2+(KWidth-200)*257/592+30+30,  KWidth, 20)];
    proLabel2.text = @"即将上线,敬请期待";
    proLabel2.textColor = [Utils colorConvertFromString:@"#101010"];
    proLabel2.font = [UIFont systemFontOfSize:15];
    proLabel2.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proLabel2];
    
    UILabel *proLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(0,250/2+(KWidth-200)*257/592+30+30+30,  KWidth, 20)];
    proLabel3.text = @"更多详情关注:www.zuke.com";
    proLabel3.textColor = [Utils colorConvertFromString:@"#101010"];
    proLabel3.font = [UIFont systemFontOfSize:15];
    proLabel3.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proLabel3];
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UiTableViewDelegata

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
      return 168*Main_Scale;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:_identify forIndexPath:indexPath];
    
    if (self.data.count > indexPath.row) {
        cell.model = self.data[indexPath.row];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    HouseDetailViewController *detailVc = [[HouseDetailViewController alloc] init];
//    
//    if (self.data.count > indexPath.row) {
//        
//        FangModel *model = self.data[indexPath.row];
//        detailVc.sn = model.sn;
//        [self.navigationController pushViewController:detailVc animated:YES];
//    }
    ParkDetailVC *parkVc = [[ParkDetailVC alloc]init];
    BuildingModel *model = self.data[indexPath.row];
    parkVc.sn = model.sn;
//    [self.navigationController pushViewController:parkVc animated:YES];
    parkVc.titleStr   = @"小区详情";

    [self presentViewController:parkVc animated:YES completion:nil];
    NSLog(@"nihao");
    
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [field endEditing:YES];
}

- (void)liaoOptionView:(RentFindParkView *)option select:(NSString *)select index:(NSInteger)index {
    
    //    optinView.frame = CGRectMake(0, 0, KWidth, KHeight);
    if ( index == 100) {
        
        district = select;
    }else if(index == 101) {
        
        NSInteger selectIndex = [select integerValue];
        rent_start = moneyStart[selectIndex];
        rent_end = moneyEnd[selectIndex];
    }
//    else if(index == 102) {
//        
//        bedroom = select;
//    }else if(index == 103) {
//        characteristic = select;
//    }
}

- (void)liaoOptionView:(RentFindParkView *)option changeFrame:(BOOL)isChange {
    
    if (isChange == YES) {
        optinView.frame = CGRectMake(0, 0, KWidth, 40);
    }else {
        optinView.frame = CGRectMake(0, 0, KWidth, KHeight);
    }
}

- (void)backActions {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)searchAction {
    
    title = field.text;
    [self reloadData];
}

@end
